package org.sepheriel.airy2d.screen;

import java.io.IOException;

import org.lwjgl.opengl.GL11;
import org.newdawn.slick.Color;
import org.newdawn.slick.opengl.Texture;
import org.newdawn.slick.opengl.TextureLoader;
import org.newdawn.slick.util.ResourceLoader;

import org.sepheriel.airy2d.exceptions.AIRYException;
import org.sepheriel.airy2d.math.Vec2;

public class Image {
	
	private Texture texture;
	private String format;
	
	private Vec2 coord;
	
	/**
	 * Image Construct0r
	 * @param path the path to the picture
	 */
	public Image(String path) {
		try {
			findFormat(path);
			this.texture = TextureLoader.getTexture(format, ResourceLoader.getResourceAsStream(path));
			this.coord = new Vec2(0, 0);
		} catch (AIRYException | IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * lookup file format 
	 * @param path relative or full path to image file
	 * @throws AIRYException if file is not compatible
	 */
	void findFormat(String path) throws AIRYException
	{
		if(path.toLowerCase().endsWith(".png"))
		{
			format = "PNG";
		}
		if(path.toLowerCase().endsWith(".tga"))
		{
			format = "TGA";
		}
		if(path.toLowerCase().endsWith(".jpg") || path.toLowerCase().endsWith(".jpeg"))
		{
			format = "JPG";
		}
		if(path.toLowerCase().endsWith(".gif"))
		{
			format = "GIF";
		}
		if(format != "")
		{
		} else {
			throw new AIRYException("No compatible file inserted!");
		}
	}
	
	Vec2 getCenter() {
		return new Vec2(this.coord.getX()+this.texture.getImageWidth()/2, this.coord.getY()+this.texture.getImageHeight()/2);
	}
	
	
	public int getWidth() {
		return (int) this.texture.getWidth();
	}
	
	public void draw() {

	GL11.glEnable(GL11.GL_TEXTURE_2D);
	GL11.glBindTexture(GL11.GL_TEXTURE_2D, texture.getTextureID());
	GL11.glBegin(GL11.GL_QUADS);
		GL11.glTexCoord2f(0, 0);
		GL11.glVertex2f(this.coord.getX(), this.coord.getY());

		GL11.glTexCoord2f(texture.getWidth(), 0);
		GL11.glVertex2f(this.coord.getX()+texture.getImageWidth(), this.coord.getY());

		GL11.glTexCoord2f(texture.getWidth(), texture.getHeight());
		GL11.glVertex2f(this.coord.getX()+texture.getImageWidth(),this.coord.getY()+texture.getImageHeight());

		GL11.glTexCoord2f(0, texture.getHeight());
		GL11.glVertex2f(this.coord.getX(),this.coord.getY()+texture.getImageHeight());
	GL11.glEnd();
	GL11.glDisable(GL11.GL_TEXTURE_2D);
	}
	
	public void free() {
		GL11.glDeleteTextures(texture.getTextureID());
	}
	
	public void draw(int x, int y) {
		this.coord.setX(x);
		this.coord.setY(y);
		draw();
	}
	
	public void draw(Vec2 co) {
		this.coord = new Vec2(co);
		draw();
	}

	public int getHeight() {
		return this.texture.getImageHeight();
	}
	

}
